import { PlusOutlined, SearchOutlined } from '@ant-design/icons'
import {
  Button,
  Checkbox,
  DatePicker,
  Form,
  Input,
  message,
  Modal,
  Select,
  Space,
  Spin,
  Table,
  Tag
} from 'antd'
import type { Dayjs } from 'dayjs'
import { FC, useEffect, useMemo, useState } from 'react'
import { useNavigate } from 'react-router'
import { isFullPermissionRole } from 'template-backend/src/common/utils/auth.utils'

import { useAuthStore } from '@/stores/authStore'
import { useNotificationStore } from '@/stores/notificationStore'
import { useScheduleStore } from '@/stores/scheduleStore'
import { useUserStore } from '@/stores/userStore'
import type { ScheduleList } from '@/types'
import { getScheduleStatusOptions, ScheduleItem } from '@/types'
import { dayjs } from '@/utils/dayjs'

import ScheduleCalendar from './components/ScheduleCalendar'
import ScheduleCommentList from './components/ScheduleCommentList'
import ScheduleStatistics from './components/ScheduleStatistics'
import TextInputModal from './components/TextInputModal'

const { Option } = Select

// 状态选项
const statusOptions = [{ value: '', label: '全部状态' }, ...getScheduleStatusOptions()]

const ScheduleList: FC = () => {
  // Router hooks
  const navigate = useNavigate()

  // Store 取值
  const scheduleList = useScheduleStore(state => state.scheduleList)
  const loading = useScheduleStore(state => state.loading)
  const page = useScheduleStore(state => state.page)
  const pageSize = useScheduleStore(state => state.pageSize)
  const total = useScheduleStore(state => state.total)
  const fetchScheduleList = useScheduleStore(state => state.fetchScheduleList)
  const fetchStatistics = useScheduleStore(state => state.fetchStatistics)
  const handleSearch = useScheduleStore(state => state.handleSearch)
  const resetSearch = useScheduleStore(state => state.resetSearch)
  const handlePageChange = useScheduleStore(state => state.handlePageChange)
  const createSchedule = useScheduleStore(state => state.createSchedule)
  const updateSchedule = useScheduleStore(state => state.updateSchedule)
  const updateScheduleStatus = useScheduleStore(state => state.updateScheduleStatus)
  const deleteSchedule = useScheduleStore(state => state.deleteSchedule)
  const addComment = useScheduleStore(state => state.addComment)
  const fetchCalendar = useScheduleStore(state => state.fetchCalendar)
  const setDate = useScheduleStore(state => state.setDate)
  const fetchUserList = useUserStore(state => state.fetchUserList)

  const userList = useUserStore(state => state.userList)
  const user = useAuthStore(state => state.user)
  const fetchUnreadNotifications = useNotificationStore(state => state.fetchUnreadNotifications)

  // useState
  const [createModalVisible, setCreateModalVisible] = useState(false)
  const [editModalVisible, setEditModalVisible] = useState(false)
  const [commentModalVisible, setCommentModalVisible] = useState(false)
  const [editingSchedule, setEditingSchedule] = useState<ScheduleItem | null>(null)
  const [commentingScheduleId, setCommentingScheduleId] = useState<string>('')
  // 用于处理已停止状态的弹窗
  const [stopReasonModalVisible, setStopReasonModalVisible] = useState(false)
  const [pendingStatusUpdate, setPendingStatusUpdate] = useState<{
    taskId: string
    newStatus: string
  } | null>(null)
  const [form] = Form.useForm()
  const [editForm] = Form.useForm()
  const [searchForm] = Form.useForm()

  // useMemo - 派生变量
  // 检查是否有删除权限
  const canDelete = useMemo(() => isFullPermissionRole(user?.role?.name || ''), [user?.role?.name])
  // useMemo内增加showStatistics变量
  const showStatistics = canDelete

  // useEffect
  useEffect(() => {
    fetchScheduleList(undefined)
    fetchUserList() // 获取用户列表用于搜索和创建/编辑表单
    // 只有管理员才获取统计数据
    if (canDelete) {
      fetchStatistics()
    }
  }, [fetchScheduleList, fetchUserList, fetchStatistics, canDelete])

  // 搜索表单处理
  const handleSearchSubmit = () => {
    searchForm.validateFields().then(values => {
      handleSearch({
        status: values.status || '',
        keyword: values.keyword || '',
        executorIds: values.executorIds || [],
        date: values.date ? (values.date as Dayjs).format('YYYY-MM-DD') : ''
      })
    })
  }

  const handleResetSearch = () => {
    searchForm.resetFields()
    resetSearch()
  }

  // 处理日历点击
  const handleCalendarClick = (date: string, status: string) => {
    // 设置日期
    setDate(date)
    searchForm.setFieldValue('date', dayjs(date))

    // 设置状态（如果点击了具体状态）
    if (status) {
      searchForm.setFieldValue('status', status)
    }

    // 触发搜索
    handleSearch({
      date,
      status: status || ''
    })
  }

  const columns = useMemo(
    () => [
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        width: 112,
        render: (status: string, record: ScheduleItem) => {
          const isFinishedStatus = status === '已完成' || status === '已停止'
          const canModifyFinishedStatus = isFullPermissionRole(user?.role?.name || '')

          // 权限检查：是否可以修改此日程
          const canModify =
            record.creatorId === user?.id ||
            record.assignedUserIds.includes(user?.id || '') ||
            isFullPermissionRole(user?.role?.name || '')

          return (
            <Select
              value={status}
              style={{ width: 90 }}
              disabled={!canModify || (isFinishedStatus && !canModifyFinishedStatus)}
              onChange={value => {
                if (value !== status) {
                  // 权限检查：如果是已完成/已停止状态且非全权限角色，不允许修改
                  if (isFinishedStatus && !canModifyFinishedStatus) {
                    message.warning('仅系统管理员和公司管理者可以修改已完成/已停止的日程')
                    return
                  }

                  // 如果选择"已停止"，需要填写原因
                  if (value === '已停止') {
                    setPendingStatusUpdate({ taskId: record.id, newStatus: value })
                    setStopReasonModalVisible(true)
                    return
                  }

                  // 使用Popconfirm进行二次确认
                  Modal.confirm({
                    title: '确认修改状态',
                    content: `确定要将状态从"${status}"修改为"${value}"吗？`,
                    okText: '确认',
                    cancelText: '取消',
                    onOk: () => handleStatusUpdate(record.id, value)
                  })
                }
              }}
            >
              {statusOptions.slice(1).map(option => (
                <Option
                  key={option.value}
                  value={option.value}
                >
                  {option.label}
                </Option>
              ))}
            </Select>
          )
        }
      },
      {
        title: '日程安排',
        dataIndex: 'title',
        key: 'title',
        width: 170,
        render: (text: string, record: ScheduleItem) => (
          <div
            className="cursor-pointer whitespace-normal break-words leading-relaxed text-blue-600 hover:text-blue-800"
            onClick={() => navigate(`/schedule/detail/${record.id}`)}
          >
            {text}
          </div>
        )
      },
      {
        title: '最新回复',
        dataIndex: 'comments',
        key: 'comments',
        width: 250,
        ellipsis: true,
        render: (comments: ScheduleItem['comments']) => (
          <ScheduleCommentList
            comments={comments || []}
            compact
          />
        )
      },
      {
        title: '创建人',
        dataIndex: 'creator',
        key: 'creator',
        width: 112,
        ellipsis: true,
        render: (creator: ScheduleItem['creator']) => (
          <div className="whitespace-normal break-words leading-relaxed">{creator.name}</div>
        )
      },
      {
        title: '执行人',
        dataIndex: 'assignedUsers',
        key: 'assignedUsers',
        width: 112,
        ellipsis: true,
        render: (assignedUsers: ScheduleItem['assignedUsers']) => (
          <div className="whitespace-normal break-words leading-relaxed">
            {assignedUsers.map(user => (
              <Tag
                className="!mb-1 !text-sm"
                key={user.id}
              >
                {user.name}
              </Tag>
            ))}
          </div>
        )
      },
      {
        title: '执行日期',
        dataIndex: 'executeDate',
        key: 'executeDate',
        width: 110,
        render: (executeDate: string | null, record: ScheduleItem) => (
          <div className="whitespace-normal break-words leading-relaxed">
            {executeDate
              ? dayjs(executeDate).format('YYYY-MM-DD')
              : dayjs(record.createTime).format('YYYY-MM-DD')}
          </div>
        )
      },
      {
        title: '截止时间',
        dataIndex: 'description',
        key: 'description',
        width: 100,
        ellipsis: true,
        render: (description: string | null) => (
          <div
            className="whitespace-normal break-words leading-relaxed"
            title={description || ''}
          >
            {description || '-'}
          </div>
        )
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
        width: 140,
        render: (createTime: Date) => (
          <div
            className="whitespace-normal break-words leading-relaxed"
            title={dayjs(createTime).format('MM月DD日 HH:mm')}
          >
            {dayjs(createTime).format('MM月DD日 HH:mm')}
          </div>
        )
      },
      // 操作列
      {
        title: '操作',
        key: 'action',
        width: 230,
        render: (record: ScheduleItem) => {
          const isFinishedStatus = record.status === '已完成' || record.status === '已停止'
          const canEdit =
            record.creatorId === user?.id ||
            record.assignedUserIds.includes(user?.id || '') ||
            isFullPermissionRole(user?.role?.name || '')

          return (
            <div className="grid grid-cols-2 gap-2">
              <Button
                variant="outlined"
                color="primary"
                onClick={() => handleAddComment(record.id)}
                disabled={!canEdit || isFinishedStatus}
              >
                回复
              </Button>
              <Button
                variant="outlined"
                color="green"
                onClick={() =>
                  Modal.confirm({
                    title: '确认完成',
                    content: '确定将该日程标记为已完成吗？',
                    okText: '完成',
                    cancelText: '取消',
                    onOk: () => handleStatusUpdate(record.id, '已完成')
                  })
                }
                disabled={isFinishedStatus}
              >
                完成
              </Button>

              <Button
                variant="outlined"
                color="primary"
                onClick={() => handleEditSchedule(record)}
                disabled={!canEdit}
              >
                编辑
              </Button>
              <Button
                variant="outlined"
                color="danger"
                onClick={() => {
                  Modal.confirm({
                    title: '确认删除',
                    content: '删除日程后，相关通知也会被删除，此操作不可恢复，确定要删除吗？',
                    okText: '确定',
                    cancelText: '取消',
                    okButtonProps: { danger: true },
                    onOk: () => handleDeleteTask(record.id)
                  })
                }}
                disabled={!canDelete}
              >
                删除
              </Button>
            </div>
          )
        }
      }
    ],
    [navigate, canDelete, user]
  )

  // 方法定义
  const handleCreateTask = async () => {
    try {
      const values = await form.validateFields()
      // 判断executeDate是否为dayjs对象，若有则格式化
      const executeDate = values.executeDate
        ? dayjs(values.executeDate).format('YYYY-MM-DD')
        : undefined
      const payload = { ...values, executeDate }
      const success = await createSchedule(payload)
      if (success) {
        message.success('日程创建成功')
        setCreateModalVisible(false)
        form.resetFields()
        fetchScheduleList(undefined)
        fetchCalendar()
      }
    } catch (error) {
      console.error('表单验证失败:', error)
    }
  }

  const handleStatusUpdate = async (taskId: string, newStatus: string, reason?: string) => {
    const success = await updateScheduleStatus({ id: taskId, status: newStatus, reason })
    if (success) {
      message.success('状态更新成功')
      fetchScheduleList(undefined)
      fetchCalendar() // 刷新日历数据（按最近区间）
    }
    return success
  }

  const handleDeleteTask = async (taskId: string) => {
    const success = await deleteSchedule(taskId)
    if (success) {
      message.success('日程删除成功')
      fetchScheduleList(undefined)
      fetchCalendar() // 刷新日历数据（按最近区间）
      // 刷新未读通知（因为相关通知可能被删除）
      fetchUnreadNotifications()
    }
  }

  // 添加回复
  const handleAddComment = (scheduleId: string) => {
    setCommentingScheduleId(scheduleId)
    setCommentModalVisible(true)
  }

  // 提交回复
  const handleSubmitComment = async (content: string) => {
    if (!content.trim()) {
      message.warning('请输入回复内容')
      return
    }

    const success = await addComment(commentingScheduleId, content.trim())
    if (success) {
      message.success('回复添加成功')
      setCommentModalVisible(false)
      fetchScheduleList(undefined)
      fetchCalendar() // 刷新日历数据（按最近区间）
    }
  }

  // 处理已停止状态（带原因）
  const handleStopReasonConfirm = async (reason: string) => {
    if (!pendingStatusUpdate) return

    if (!reason.trim()) {
      message.warning('请输入停止原因')
      return
    }

    const success = await handleStatusUpdate(
      pendingStatusUpdate.taskId,
      pendingStatusUpdate.newStatus,
      reason
    )

    if (success) {
      setStopReasonModalVisible(false)
      setPendingStatusUpdate(null)
    }
  }

  // 编辑日程
  const handleEditSchedule = (schedule: ScheduleItem) => {
    setEditingSchedule(schedule)
    editForm.setFieldsValue({ title: schedule.title })
    setEditModalVisible(true)
  }

  const handleEditCancel = () => {
    setEditModalVisible(false)
    editForm.resetFields()
    setEditingSchedule(null)
  }

  // 提交编辑
  const handleSubmitEdit = async () => {
    try {
      const values = await editForm.validateFields()
      if (!editingSchedule) return

      const success = await updateSchedule({ id: editingSchedule.id, title: values.title })
      if (success) {
        message.success('日程编辑成功')
        handleEditCancel()
        fetchScheduleList(undefined)
        fetchCalendar() // 刷新日历数据（按最近区间）
      }
    } catch (error) {
      console.error('表单验证失败:', error)
    }
  }

  return (
    <div className="w-full max-w-full">
      {/* 顶部左右布局：左侧统计，右侧日历 */}
      <div className="mb-2 w-full">
        <div className="flex flex-col gap-4 md:flex-row">
          {/* 左边：日历区域，统计卡不显示时铺满，否则采用原有宽度 */}
          <div className={showStatistics ? 'w-full md:w-[70%] lg:w-[75%]' : 'w-full'}>
            <ScheduleCalendar onDateStatusClick={handleCalendarClick} />
          </div>
          {/* 右边：统计卡片，仅super/admin显示 */}
          {showStatistics && (
            <div className="w-full md:w-[30%] lg:w-[25%]">
              <ScheduleStatistics />
            </div>
          )}
        </div>
      </div>

      {/* 搜索和筛选区域 */}
      <div className="mb-4 flex justify-between">
        <Form
          form={searchForm}
          layout="inline"
          onFinish={handleSearchSubmit}
        >
          <Form.Item name="status">
            <Select
              placeholder="选择状态"
              style={{ width: 120 }}
              allowClear
            >
              {statusOptions.map(option => (
                <Option
                  key={option.value}
                  value={option.value}
                >
                  {option.label}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="keyword">
            <Input
              placeholder="搜索日程标题或内容"
              allowClear
              style={{ width: 200 }}
            />
          </Form.Item>
          <Form.Item name="executorIds">
            <Select
              mode="multiple"
              placeholder="选择执行人"
              style={{ width: 200 }}
              allowClear
            >
              {userList
                .filter(user => user.role?.name !== '系统管理员')
                .map(user => (
                  <Option
                    key={user.id}
                    value={user.id}
                  >
                    {user.name}
                  </Option>
                ))}
            </Select>
          </Form.Item>
          <Form.Item name="date">
            <DatePicker
              placeholder="选择日期"
              format="YYYY-MM-DD"
              style={{ width: 150 }}
              allowClear
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button
                type="primary"
                htmlType="submit"
                icon={<SearchOutlined />}
              >
                搜索
              </Button>
              <Button onClick={handleResetSearch}>清空</Button>
            </Space>
          </Form.Item>
        </Form>
        <Button
          variant="outlined"
          color="primary"
          icon={<PlusOutlined />}
          onClick={() => setCreateModalVisible(true)}
        >
          新建日程
        </Button>
      </div>

      <Spin spinning={loading}>
        <Table
          rowKey="id"
          bordered
          columns={columns}
          dataSource={scheduleList}
          pagination={{
            current: page,
            pageSize: pageSize,
            total: total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: total => `共 ${total} 条记录`,
            onChange: handlePageChange,
            onShowSizeChange: (current, size) => handlePageChange(current, size)
          }}
        />
      </Spin>

      {/* 创建日程弹窗 */}
      <Modal
        title="新建日程"
        open={createModalVisible}
        onCancel={() => {
          setCreateModalVisible(false)
          form.resetFields()
        }}
        footer={[
          <Button
            key="cancel"
            onClick={() => {
              setCreateModalVisible(false)
              form.resetFields()
            }}
          >
            取消
          </Button>,
          <Button
            key="create"
            variant="outlined"
            color="primary"
            onClick={handleCreateTask}
          >
            创建
          </Button>
        ]}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{ title: '', description: '', assignedUserIds: [], isPrivate: false }}
        >
          <Form.Item
            name="title"
            label="日程安排"
            rules={[{ required: true, message: '请输入日程安排' }]}
          >
            <Input
              placeholder="请输入日程安排"
              maxLength={100}
            />
          </Form.Item>

          <Form.Item
            name="executeDate"
            label={
              <>
                执行日期（选填）
                <span style={{ color: '#999', fontWeight: 400, marginLeft: 4 }}>
                  （如不填写则按创建日期）
                </span>
              </>
            }
          >
            <DatePicker
              style={{ width: '100%' }}
              placeholder="如不填写则按创建日期"
              format="YYYY-MM-DD"
              allowClear
            />
          </Form.Item>

          <Form.Item
            name="description"
            label="截止时间"
          >
            <Input
              placeholder="请输入截止时间（备注）"
              maxLength={200}
            />
          </Form.Item>

          <Form.Item
            name="assignedUserIds"
            label="执行人"
            rules={[{ required: true, message: '请选择执行人' }]}
          >
            <Select
              mode="multiple"
              placeholder="请选择执行人"
              style={{ width: '100%' }}
            >
              {userList
                .filter(user => user.role?.name !== '系统管理员')
                .map(user => (
                  <Option
                    key={user.id}
                    value={user.id}
                  >
                    {user.name}
                  </Option>
                ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="isPrivate"
            label="权限设置"
            valuePropName="checked"
          >
            <Checkbox>仅相关人员可查看该日程</Checkbox>
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑日程弹窗 */}
      <Modal
        title="编辑日程"
        open={editModalVisible}
        onCancel={handleEditCancel}
        footer={[
          <Button
            key="cancel"
            onClick={handleEditCancel}
          >
            取消
          </Button>,
          <Button
            key="edit"
            variant="outlined"
            color="primary"
            onClick={handleSubmitEdit}
          >
            保存
          </Button>
        ]}
        width={500}
      >
        <Form
          form={editForm}
          layout="vertical"
        >
          <Form.Item
            name="title"
            label="日程安排"
            rules={[{ required: true, message: '请输入日程安排' }]}
          >
            <Input
              placeholder="请输入日程安排"
              maxLength={100}
            />
          </Form.Item>
        </Form>
      </Modal>

      {/* 回复弹窗 */}
      <TextInputModal
        title="添加回复"
        open={commentModalVisible}
        onCancel={() => {
          setCommentModalVisible(false)
          setCommentingScheduleId('')
        }}
        onConfirm={handleSubmitComment}
        placeholder="请输入回复内容..."
        rows={6}
        maxLength={500}
        confirmText="发送"
      />

      {/* 已停止原因弹窗 */}
      <TextInputModal
        title="填写停止原因"
        open={stopReasonModalVisible}
        onCancel={() => {
          setStopReasonModalVisible(false)
          setPendingStatusUpdate(null)
        }}
        onConfirm={handleStopReasonConfirm}
        placeholder="请输入停止原因"
        rows={4}
        maxLength={200}
      />
    </div>
  )
}

export default ScheduleList
